﻿using Abp.Dependency;
using System.IO;
using UAParser.FormFactor;
using UAParser.FormFactor.Models;

namespace Mt.Site.Core.AccessStatistics
{
    public class UserAgentParser : IUserAgentParser, ISingletonDependency
    {
        private readonly IAppFolders _appFolders;
        private static IUAParser _uAParser;
        private IUAParser UAParser
        {
            get
            {
                if (_uAParser == null)
                {
                    if (File.Exists(FilePath))
                    {
                        using (FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read))
                        using (var reader = new StreamReader(fs))
                        {
                            _uAParser = Parser.FromYaml(reader.ReadToEnd());
                        }
                    }
                    else
                    {
                        _uAParser = Parser.GetDefault();
                    }
                }
                return _uAParser;
            }
        }

        private readonly string FilePath;
        public UserAgentParser(IAppFolders appFolders)
        {
            _appFolders = appFolders;
            FilePath = Path.Combine(_appFolders.TempFolder, "Statics/regexes.yaml");
        }


        public ClientInfo Parse(string userAgent)
        {
            return UAParser.Parse(userAgent);
        }
    }
}
